package com.fungo.orderservice.service;

import com.fungo.orderservice.model.Order;
import com.fungo.orderservice.repository.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class OrderService {

    private final OrderRepository orderRepository;
    private final UserService userService;
    
    @Autowired
    public OrderService(OrderRepository orderRepository, UserService userService) {
        this.orderRepository = orderRepository;
        this.userService = userService;
    }
    
    /**
     * Get all orders for a specific user, after verifying the user exists
     */
    public List<Order> getOrdersForUser(String userId) {
        // First verify that the user exists by calling the user-service
        boolean userExists = userService.userExists(userId);
        
        if (!userExists) {
            log.warn("Attempted to get orders for non-existent user: {}", userId);
            return Collections.emptyList();
        }
        
        // User exists, now get their orders
        log.info("Fetching orders for user: {}", userId);
        return orderRepository.findByUserId(userId);
    }
    
    /**
     * Create a new order
     */
    public Order createOrder(Order order) {
        // First verify that the user exists
        boolean userExists = userService.userExists(order.getUserId());
        
        if (!userExists) {
            log.error("Cannot create order for non-existent user: {}", order.getUserId());
            throw new IllegalArgumentException("User does not exist");
        }
        
        log.info("Creating new order for user: {}", order.getUserId());
        return orderRepository.save(order);
    }
} 